import React, { useState } from 'react'
import '@/assets/css/confirm.scoped.css'
import { Checkbox } from 'antd-mobile'

export default () =>
{
    let rid = React.params('rid')
    let [DateShow, SetDateShow] = React.useState(false)
    let [GuestShow, SetGuestShow] = React.useState(false)
    let [CouponShow, SetCouponShow] = React.useState(false)
    let [PayShow, SetPayShow] = React.useState(false)
    let [price, SetPrice] = React.useState(0)
    let [OriginPrice, SetOriginPrice] = React.useState(0)
    let [day, SetDay] = React.useState(0)
    let [guest, SetGuest] = useState([])
    let [coupon, SetCoupon] = React.useState([])
    let [room, SetRoom] = useState({
        flag_text: []
    })

    //订单信息
    let [order, SetOrder] = React.useState({
        roomid: rid,
        busid: React.business.id,
        remark: '',
        //价格信息
        origin_price: room.price,
        price: '',
        //优惠券
        couponid:'',
        couponstr: '',
        //日期
        datestr: '',
        starttime: 0,
        endtime: 0,
        //住客
        guest: '',
        gueststr: '',
        guestids: [],
        //支付方式
        paystr: '余额支付',
        pay: 'money'
    })

    //支付信息
    let [paylist, SetPay] = React.useState([[
        {label: '余额支付', value: 'money'},
        {label: '微信支付', value: 'wx'},
        {label: '支付宝支付', value: 'zfb'},
    ]])

    React.useEffect(() => {
        RoomData()
        GuestData()
        CouponData()
    }, [])

    //订单信息有变化，就重新计算价格
    React.useEffect(() => {
        Total()
    }, [order])

    //计算总价格方法
    const Total = () =>
    {
        var starttime = order.starttime
        var endtime = order.endtime

        //时间差
        var day:any = endtime - starttime
        day = day / 86400
        day = day.toFixed(0)
        day = parseInt(day)

        //原价 时间差*房间原价
        var origin_price = day * parseFloat(room.price ?? 0)

        var price = origin_price

        //是否有选择优惠券
        if(order.couponid)
        {
            var rate = 1
            var list:any = coupon[0]
            //找寻当前所选择的优惠券信息
            list.map((item:any) => 
            {
                if(item.value == order.couponid)
                {
                    rate = item.rate
                }
            })

            //计算折扣后的价格
            price = origin_price*rate
        }

        //修改价格
        SetPrice(price)
        SetOriginPrice(origin_price)
        SetDay(day)
    }

    //房间信息
    const RoomData = async () =>
    {
        var result = await React.request.post('/room/info', {rid})

        if(result.code == 0)
        {
            React.toast(result.msg, 'back', 'fail')
            return false
        }

        SetRoom(result.data.room)
    }

    // 住客信息
    const GuestData = async () =>
    {
        var result = await React.request.post('/room/guest', {busid: React.business.id})

        if(result.code == 0)
        {
            React.toast(result.msg, null, 'fail')
            return false
        }
        
        SetGuest(result.data)
    }

    //优惠券信息
    const CouponData = async () => 
    {
        var result = await React.request.post('/room/coupon', {busid: React.business.id})

        if(result.code == 1)
        {
            var list:any = []

            result.data.map((item:any) => {
                list.push({
                    label: `${item.coupon.title}-${item.coupon.rate*10}折`,
                    value: item.id,
                    rate: item.coupon.rate
                })
            })

            //给二维数组结构
            list = [list]
            SetCoupon(list)
        }
    }

    //clear
    const clear = async () =>
    {   
        SetOrder({
            ...order,
            couponstr:'',
            couponid: '',
        })
    }

    // 修改日期
    const DateConfirm = async (val: any) =>
    {
        SetDateShow(false)

        // var datestr = `2024-03-20 - 2024-03-25` 转换标准时间
        const options = {month: 'long', day: 'numeric'}
        var datestr = `${new Date(val[0]).toLocaleDateString('zh-cn', options)} - ${new Date(val[1]).toLocaleDateString('zh-cn', options)}`

        //获取到开始时间和结束时间
        //标准时间转换为时间戳
        var starttime = Date.parse(new Date(val[0]).toLocaleDateString())/1000
        var endtime = Date.parse(new Date(val[1]).toLocaleDateString())/1000
        
        SetOrder({
            ...order,
            starttime,
            endtime,
            datestr
        })
    }

    //选择住客人
    const GuestChange = async (value) => 
    {
        SetOrder({
            ...order,
            guestids: value
        })
    }

    const Checked =(id) =>
    {
        var checkid = order.guestids.indexOf(id);
        var checked = [...order.guestids];
        if (checkid === -1) {
            checked.push(id); // 添加选中项
        } else {
            checked.splice(checkid, 1); // 取消选中
        }
        SetOrder({ ...order, guestids: checked });
    }
    //确认住客人
    const GuestConfirm = async () => 
    {
        SetGuestShow(false)

        var gueststr = ''

        guest.map((item, key) => {
            if(order.guestids.includes(item.id)) gueststr += `${item.nickname}，`
        })

        gueststr = gueststr.substring(0, gueststr.length - 1);
        
        SetOrder({
            ...order,
            gueststr
        })
    }

    //确认选择优惠券
    const CouponConfirm = async (value: any) =>
    {
        SetCouponShow(false)

        var couponstr = ''

        //获取picker第一项
        var list:any = coupon[0]

        list.map((item:any) => {
        if(item.value == value[0])
        {
            couponstr = item.label
        }
        })

        SetOrder({
            ...order,
            couponstr,
            couponid: value[0],
        })


    }

    //选择支付方式
    const PayConfirm = async (value: any) =>
    {
        SetPayShow(false)

        var paystr = ''

        //获取picker第一项
        var list:any = paylist[0]

        list.map((item:any) => 
        {
            if(item.value == value[0])
            {
                paystr = item.label
            }
        })
        
        SetOrder({
            ...order,
            paystr,
            pay: value[0],
        })
    }

    //输入订单备注
    const RemarkChange = async (e:any) =>
    {
        SetOrder({
            ...order,
            remark:e
        })
    }

    //提交订单
    const confirm = async () =>
    {
        //弹出提示框
        var result = await React.UI.Dialog.confirm({content: '是否确认提交订单'})

        if(!result) return false

        var data = {
            busid: order.busid,
            roomid: order.roomid,
            guest: order.guestids.join(','),
            starttime: order.starttime,
            endtime: order.endtime,
            couponid: order.couponid ? order.couponid : 0,
            remark: order.remark,
            pay: order.pay ? order.pay : 'money'
        }

        if(!data.starttime || !data.endtime)
        {
            React.toast('请选择入住时间', null, 'fail')
            return false
        }

        // if(!data.endtime)
        // {
        //     React.toast('请选择结束时间', null, 'fail')
        //     return false
        // }

        if(!data.guest)
        {
            React.toast('请选择住客信息', null, 'fail');
            return false
        }

        var result = await React.request.post('/room/add', data)

        if(result.code == 0)
        {
            React.toast(result.msg, null, 'fail');
        }else
        {
            //跳转到订单详情界面
            React.toast(result.msg, result.url, 'success');
        }
    }

    return (
        <>
            <div className="top"><div>下单提交</div></div>

            <div className='skeleton'>
                {/* 房间信息 */}
                <div className="detail">
                    <div className="thumb">
                        <img src={room.thumb_text} alt="" />
                    </div>
                    <div className="right">
                        <p>{room.name}</p>
                        <p>￥{room.price} / 晚</p>
                        <div className="tips">
                            {room.flag_text && room.flag_text.map((flag:any, index:any) => <span key={index}> {flag} </span>)}
                        </div>
                    </div>
                </div>

                {/* 表单信息 */}
                <div className='skeleton_rect'>
                    {/* 入住日期 */}
                    <div className='item'>
                        <label>入住日期</label>

                        <React.UI.Input type="text" className="date" placeholder="请选择入住日期" value={order.datestr} onClick={() => SetDateShow(true)} />
                            
                        {/* <label></label> */}

                        {/* 日期选择 */}
                        <React.UI.CalendarPicker
                            visible={DateShow}
                            min={new Date()}
                            selectionMode='range'
                            onClose={() => SetDateShow(false)}
                            onMaskClick={() => SetDateShow(false)}
                            onConfirm={DateConfirm}
                        >
                        </React.UI.CalendarPicker>
                    </div>

                </div>
                <div className='skeleton_rect'>
                    {/* 住客信息 */}
                    <div className='item'>
                        <label>住客信息</label>

                        {/* <button type="button" className="btn">
                            <a>添加/选择</a>
                        </button> */}

                        <React.UI.Input type="text" className="date" placeholder="请添加或选择住客信息" value={order.gueststr} onClick={() => SetGuestShow(true)}/>

                        {/* 弹出层 */}
                        <React.UI.CenterPopup visible={GuestShow} closeOnMaskClick={true} onMaskClick={() => SetGuestShow(false)} bodyStyle={{ marginLeft: '-40px', minWidth: '54vh'}}>
                            <Checkbox.Group value={order.guestids} onChange={GuestChange}>
                                {guest.map((item, key) => (
                                    <React.UI.List.Item style={{'--align-items': 'center'}}
                                        prefix={<Checkbox className='cbox' value={item.id} onClick={(e) => e.stopPropagation()}/>} 
                                        key={key} 
                                        value={order.guestids} 
                                        description={`${item.mobile}\u00A0\u00A0\u00A0\u00A0\u00A0 ${item.gender_text}`}
                                        onClick={() => Checked(item.id)}
                                        >
                                        {item.nickname}
                                    </React.UI.List.Item>
                                ))}
                            </Checkbox.Group>
                            <React.UI.Button style={{'--border-radius': '0px'}} block type='button' color='primary' size='large' onClick={GuestConfirm}>确定选择</React.UI.Button>
                        </React.UI.CenterPopup>
                    
                    </div>
                </div>

                {/* 表单信息 */}
                <div className="skeleton_rect">
                    {/* 优惠券 */}
                    {coupon[0] && 
                        <div className='item'>
                            <label>优惠券</label>
                            <React.UI.Input type="text" className="date" placeholder="请选择优惠券" value={order.couponstr} onClick={() => SetCouponShow(true)} clearable={true} onClear={clear} />
                        </div>
                    }

                    {/* 弹框选项 */}
                    <React.UI.Picker
                        columns={coupon}
                        visible={CouponShow}
                        onClose = {() => SetCouponShow(false)}
                        onConfirm={CouponConfirm}
                    >
                    </React.UI.Picker>

                    {/* 支付方式 */}
                    <div className='item'>
                        <label>支付方式</label>
                        <React.UI.Input type="text" className="date" placeholder="请选择支付方式" value={order.paystr} onClick={() => SetPayShow(true)} />
                    </div>

                    <React.UI.Picker
                        columns={paylist}
                        visible={PayShow}
                        onClose={() => SetPayShow(false)}
                        onConfirm={PayConfirm}
                    >
                    </React.UI.Picker>

                    {/* 订单备注 */}
                    <div className='item'>
                        <label>订单备注</label>
                        <React.UI.Input type="text" className="date" placeholder="请输入订单备注" value={order.remark} onChange={RemarkChange} clearable />
                    </div>
                </div>

                <div className="skeleton_price">
                    <div className="tips">房间费用</div>
                    <div className="prices">
                        <span>￥{OriginPrice}</span>
                        <span>共 {day} 晚</span>
                    </div>
                </div>
            </div>

            <div className="comfirm_foot-bar">
                {coupon[0] && price == OriginPrice ?
                    <div className="text">
                        <span>总价:</span>
                        <span>￥{price}</span>
                    </div>:
                    <div className="text">
                        <span>优惠价格:</span>
                        <span>￥{price}</span>
                        <s>原价：￥{OriginPrice}</s>
                    </div>
                }

                <React.UI.Button onClick={confirm} color='primary' disabled={room.state ? false: true}>提交订单</React.UI.Button>
            </div>
        </>
    )
}